<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 异步调用组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Ajax extends Widget
{
	
    /**
     * 构造函数,初始化组件
     *
     * @access public
     * @param mixed $request request对象
     * @param mixed $response response对象
     * @param mixed $params 参数列表
     */
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);
		
		/** 插件接口 */
		//HOOK PLUG_Ajax($this);
    }
	
    /**
     * 针对rewrite验证的请求返回
     *
     * @access public
     * @return void
     */
    public function rewriteCallback()
    {
        exit('OK');
    }

    public function changeTheme()
    {
        /** 管理员以上权限 */
        $this->user->pass('admin');
		
		$theme = $this->request->filter('strip_tags')->theme;
        if (is_dir($this->options->themeFile($theme))) {
			
            /** 删除原外观设置信息 */
            $this->widget('Widget_Abstract_Options')->delete('theme:' . $this->options->theme);
            $this->widget('Widget_Abstract_Options')->update('theme', $theme);

            $configFile = $this->options->themeFile($theme, 'functions.php');
   
            if (file_exists($configFile)) {
                require_once $configFile;
                
                if (function_exists('themeConfig')) {
                    $form = new Form();
                    themeConfig($form);
                    $options = $form->getValues();

                    if ($options) {
                        $this->widget('Widget_Abstract_Options')->insert(array(
                            'name'  =>  'theme:' . $theme,
                            'value' =>  serialize($options)
                        ));
                    }
                }
            }			

			$this->result->set(0, _t("外观已经改变"));
        } else {
			$this->result->set(-1, _t("您选择的风格不存在"));
        }
    }

    /**
     * 异步请求入口
     *
     * @access public
     * @return void
     */
    public function action()
    {

        if (!$this->request->isAjax()) {
			$this->result->set(404, _t('请求的资源不存在'));
        }

        $this->on($this->request->is('rewrite'))->rewriteCallback();
        $this->on($this->request->is('changeTheme'))->changeTheme();
    }
}
